class Solution {
    public int findMaxLength(int[] nums) {
        int res = 0, n = nums.length, preSum = 0;
        int[] hash = new int[2 * n + 1];
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] == 0) {
                nums[i] = -1;
            }
        }
        for (int i = 0; i < n; ++i) {
            preSum += nums[i];
            if (preSum == 0) {
                res = i + 1;
            } else if (hash[preSum + n] == 0) {
                hash[preSum + n] = i + 1;
            } else {
                res = Math.max(res, i + 1 - hash[preSum + n]);
            }
        }
        return res;
    }
}
